package com.arykow.engine.onwebapp.server;

import java.io.InputStream;
import java.nio.charset.Charset;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.xml.sax.InputSource;

import com.sun.syndication.io.XmlReader;

public class OPMLParser {
	private OPMLSourceTransformer transformer = new OPMLSourceTransformer();

	public void parse(InputStream inputStream, Charset charset, OPMLParserListener listener) {
		JSONArray feeds = null;
		try {
			InputSource inputSource = new InputSource(new XmlReader(inputStream));
			//InputSource inputSource = new InputSource(new InputStreamReader(inputStream, charset));
			DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputSource));
			SourceTransformResult result = transformer.apply(source);
			feeds = JSONArray.class.cast(result.asJSON());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		int size = feeds.size();
		listener.listenStart(size);
		for (int index = 0; index < size; index++) {
			JSONObject feed = feeds.getJSONObject(index);
			String text = feed.getString("text");
			String title = feed.getString("title");
			String xmlUrl = feed.getString("xmlUrl");
			String htmlUrl = feed.getString("htmlUrl");
			listener.listenElement(index, text, title, xmlUrl, htmlUrl);
		}
		listener.listenStop();
	}
}
